package cn.formaggie.interceptor;

import cn.formaggie.annotation.CheckTwiceSubmit;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class TwiceSubmitInterceptor extends HandlerInterceptorAdapter{

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod= (HandlerMethod) handler;
            Method method=handlerMethod.getMethod();
            CheckTwiceSubmit annotation=method.getAnnotation(CheckTwiceSubmit.class);
            //如果方法上面有该注解，就进行判断
            if(annotation!=null){
                if(isTiwceSubmit(request)){
                    return false;
                }else{
                    return true;
                }
            }
            return true;
        }else {
            return super.preHandle(request, response, handler);
        }
    }

    private boolean isTiwceSubmit(HttpServletRequest request) {
        String params= JSON.toJSONString(request.getParameterMap());
        String url=request.getRequestURI();
        Map<String,String> map=new HashMap<>();
        map.put(url,params);
        String nowUrlParams=map.toString();

        Object preUrlParams=request.getSession().getAttribute("repeatData");
        if(preUrlParams==null)//如果上一个数据为null,表示还没有访问页面
        {
            request.getSession().setAttribute("repeatData", nowUrlParams);
            return false;
        }
        else//否则，已经访问过页面
        {
            if(preUrlParams.toString().equals(nowUrlParams))//如果上次url+数据和本次url+数据相同，则表示重复提交数据
            {
                return true;
            }
            else//如果上次 url+数据 和本次url加数据不同，则不是重复提交
            {
                request.getSession().setAttribute("repeatData", nowUrlParams);
                return false;
            }

        }
    }
}
